import React, { Component } from 'react';

import { Table, Tree, Collapse, Icon, Select, Tooltip } from '@knownsec/react-component';
import s from './style.module.less';
import CopyText from '@/components/CopyBoard';

import safeEvent from '@/assets/images/safeEvent.png';
import loophole from '@/assets/images/loophole.png';
import folderIcon from '@/assets/svg/folder.svg';
import highIcon from '@/assets/svg/high.svg';
import lowIcon from '@/assets/svg/low.svg';

import mediumIcon from '@/assets/svg/medium.svg';
import lineIcon from '@/assets/svg/line.svg';
import netIcon from '@/assets/svg/net.svg';
import netgreyIcon from '@/assets/svg/netgrey.svg';
import optionIcon from '@/assets/svg/option.svg';
import regularIcon from '@/assets/svg/regular.svg';
import { Link } from 'react-router-dom';
import cn from 'classnames';
import SelfTable from './table';
import { WARNING_SECURITYEVENT_MAP2 } from '@/common/common';
import { vulTop10 } from '~/API';
const { Panel } = Collapse;

class Allevent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selfTableData: {},
      loading: true,
      treeData: [{}],
      treeNum: { fileNum: 0, urlNum: 0 },
      dataList: [],
      selectNode: ['0-0', '0-0-0'],
      columns: [
        {
          title: '风险URL',
          dataIndex: 'url',
          render: (e, row) => {
            return (
              <span
                className={s.top10sp}
                onClick={() => {
                  if (
                    this.props.sid &&
                    this.props.sid !== 'undefined' &&
                    this.props.sid !== 'null'
                  ) {
                    return;
                  }
                  this.props.pfn({ keyNum: '漏洞', searchInfo: e });
                }}
              >
                {e}
              </span>
            );
          },
        },
        {
          title: '高危漏洞数',
          dataIndex: 'count',
          className: 'bwidth',
        },
      ],
    };
  }
  async getTop10() {
    this.setState({ loading: true });
    const res = await vulTop10(this.props.targetId);
    if (res.status === 'success') {
      this.setState({ dataList: res.data.top, loading: false });
    } else {
      this.setState({ dataList: [], loading: false });
    }
  }
  componentDidUpdate(prevProps, preState) {}
  componentDidMount() {
    if (this.props.targetId) {
      this.getTop10();
    }
    this.togetherData();
  }
  togetherData() {
    const { task_events, target_url } = this.props.alleventData;
    if (!task_events && this.state.treeNum.fileNum) {
      return false;
    }
    const table = {};
    let fileNum = 0;
    let urlNum = 0;
    const eventD = task_events || {};
    const activeObj = (key, arr) => {
      arr.forEach((e) => {
        if (e.event_name === 'statistics') {
          return;
        }
        const url = e.detail.url;
        const num = url.split('/');
        if (num[num.length - 1].includes('.')) {
          fileNum += 1;
        } else {
          urlNum += 1;
        }
        if (key === 'change_check') {
          const type = 2;
          !table['篡改'] && (table['篡改'] = { url: [], type });
          table['篡改'].url.push(url);
        } else if (key === 'risk_link') {
          const type = e.detail.confidence_level;
          !table['风险外链'] && (table['风险外链'] = { url: [], type });
          table['风险外链'].url.push(url);
        } else if (key === 'securityEvent') {
          const type = e.detail.severity ? e.detail.severity : e.severity;
          const name = WARNING_SECURITYEVENT_MAP2[e.event_name];
          !table[name] && (table[name] = { url: [], type });
          table[name].url.push(url);
        } else {
          const type = e.detail.severity ? e.detail.severity : e.severity;
          const zh_cn = e.detail.name.zh_cn;
          !table[zh_cn] && (table[zh_cn] = { url: [], type });
          table[zh_cn].url.push(url);
        }
      });
    };
    Object.entries(eventD).forEach(([key, val]) => {
      activeObj(key, val);
    });
    if (Object.keys(table)[0]) {
      const children = [];
      Object.entries(table).forEach(([key, val]) => {
        const src = val.type > 3 ? highIcon : val.type > 2 ? mediumIcon : lowIcon;
        children.push({
          type: val.type,
          title: `${key}(${val.url.length})`,
          icon: <img src={src} />,
          children: val.url.map((e) => {
            return {
              title: <CopyText maxWidth={'600px'} text={e}/>,
              icon: <img src={folderIcon} />,
            };
          }),
        });
      });
      children.sort((a, b) => {
        return b.type - a.type;
      });
      const treeData = [
        {
          title: target_url,
          icon: <img src={netIcon} />,
          children,
        },
      ];
      this.setState({ treeNum: { fileNum, urlNum }, treeData });
    }
  }
  showNum(e) {
    return e >= 0 ? e : '-';
  }
  render() {
    const { summary, target_url, risk_distribution, risk_detail, task_info } =
      this.props.alleventData;
    const { treeNum, treeData, dataList, selectNode, columns } = this.state;

    return (
      <div className={s.wangall}>
        <div className={s.title}>风险分布</div>
        <div className={s.taskitem}>
          {risk_distribution?.securityEvent && (
            <div className={s.item}>
              <div className={s.left}>
                <div className={s.imgbox}>
                  <img src={safeEvent} alt="" />
                </div>
                <div>
                  <p>安全事件</p>
                  <p>{risk_distribution?.securityEvent?.num}</p>
                </div>
              </div>
              <div className={s.right}>
                <p className={s.p2rm}>
                  高危：
                  <span className={s.highwords}>
                    {this.showNum(risk_distribution?.securityEvent?.HIGH)}
                  </span>
                </p>
                <p className={s.p2rm}>
                  中危：
                  <span className={s.midwords}>
                    {this.showNum(risk_distribution?.securityEvent?.MEDIUM)}
                  </span>
                </p>
                <p className={s.p2rm}>
                  低危：
                  <span className={s.lowwords}>
                    {this.showNum(risk_distribution?.securityEvent?.LOW)}
                  </span>
                </p>
              </div>
            </div>
          )}
          {risk_distribution?.vul && (
            <div className={cn(s.item,s.itemVul)}>
              <div className={cn(s.left, s.vulLeft)}>
                <div className={s.imgbox}>
                  <img src={safeEvent} alt="" />
                </div>
                <div>
                  <p>漏洞</p>
                  <p>{risk_distribution?.vul?.num}</p>
                </div>
              </div>
              <div className={cn(s.right, s.vulRight)}>
                <p className={s.tp}>
                  严重：
                  <span className={s.deepwords}>
                    {this.showNum(risk_distribution?.vul?.CRITICAL)}
                  </span>
                </p>
                <p className={s.tp}>
                  高危：
                  <span className={s.highwords}>{this.showNum(risk_distribution?.vul?.HIGH)}</span>
                </p>
                <p className={s.tp}>
                  中危：
                  <span className={s.midwords}>{this.showNum(risk_distribution?.vul?.MEDIUM)}</span>
                </p>
                <p className={s.tp}>
                  低危：
                  <span className={s.lowwords}>{this.showNum(risk_distribution?.vul?.LOW)}</span>
                </p>
              </div>
            </div>
          )}
          {risk_distribution?.risk_link && (
            <div className={s.item}>
              <div className={s.left}>
                <div className={s.imgbox}>
                  <img src={safeEvent} alt="" />
                </div>
                <div>
                  <p>风险外链</p>
                  <p>{risk_distribution?.risk_link?.num}</p>
                </div>
              </div>
              <div className={s.right}>
                <p className={s.p2rm}>
                  高危：
                  <span className={s.highwords}>
                    {this.showNum(risk_distribution?.risk_link?.HIGH)}
                  </span>
                </p>
                <p className={s.p2rm}>
                  中危：
                  <span className={s.midwords}>
                    {this.showNum(risk_distribution?.risk_link?.MEDIUM)}
                  </span>
                </p>
                <p className={s.p2rm}>
                  低危：
                  <span className={s.lowwords}>
                    {this.showNum(risk_distribution?.risk_link?.LOW)}
                  </span>
                </p>
              </div>
            </div>
          )}
          {risk_distribution?.change_check && (
            <div className={s.item}>
              <div className={s.left}>
                <div className={s.imgbox}>
                  <img src={safeEvent} alt="" />
                </div>
                <div>
                  <p>篡改</p>
                  <p>{risk_distribution?.change_check?.num}</p>
                </div>
              </div>
              <div className={s.right}>
                <p className={s.p2rm}>
                  低危：
                  <span className={s.lowwords}>
                    {this.showNum(risk_distribution?.change_check?.LOW)}
                  </span>
                </p>
              </div>
            </div>
          )}
        </div>
        <div className={s.title}>风险详情</div>
        {risk_detail && <SelfTable selfTableData={risk_detail} type={this.props.type} />}
        <div className={s.title}>高危漏洞数最多的风险URL TOP10</div>
        <Table
          columns={columns}
          data={dataList}
          tableLoading={this.state.loading}
          loadingLabel=""
        ></Table>
        <div className={s.title}>威胁分布详情</div>
        <Collapse defaultActiveKey={['1']} expandIconPosition="right">
          <Panel
            header={
              <span>
                <img src={netgreyIcon} />
                &ensp;{target_url}
              </span>
            }
            key="1"
          >
            <div className={s.dangerous}>
              <div className={s.account}>
                <p>
                  <img src={lineIcon} /> 统计
                </p>
                <p>
                  <img src={optionIcon} /> 文件数--{treeNum.fileNum}
                </p>
                <p>
                  <img src={optionIcon} /> URL数--{treeNum.urlNum}
                </p>
              </div>
              <Tree showIcon treeData={treeData} defaultExpandAll />
            </div>
          </Panel>
        </Collapse>
      </div>
    );
  }
}

export default Allevent;
